package com.coder520.mamabike.security;

import com.alibaba.fastjson.JSON;
import com.coder520.mamabike.common.Const;
import com.coder520.mamabike.common.ServerResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by ASUS on 2017/8/14.
 */
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    /**异常处理*/
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        Integer code = (Integer) request.getAttribute("head-error");
        ServerResponse serverResponse = null;
        if (code != null && Const.SecurityCode.codeOf(code).getDesc()!=null) {
            serverResponse =  ServerResponse.createByError(Const.SecurityCode.codeOf(code).getDesc());
        }

        try {
            //设置跨域请求 请求结果json刷到响应里 前后端分离的时候都要设置
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEADER");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, user-token, Content-Type, Accept, version, type, platform");
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.getWriter().write(JSON.toJSONString(serverResponse));
            response.flushBuffer();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}
